import React, { useState } from 'react';
import { Card, Button, message, Spin, Result } from 'antd';
import { FileAddOutlined, DeleteOutlined } from '@ant-design/icons';
import { pdfApi } from '../../services/api';
import { handleApiError, downloadFile } from '../../utils/error';
import FileUploader from '../../components/common/FileUploader';

const PDFMerger: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [files, setFiles] = useState<File[]>([]);
  const [error, setError] = useState<string | null>(null);

  const handleUpload = async (newFiles: File[]) => {
    setFiles(prev => [...prev, ...newFiles]);
  };

  const handleMerge = async () => {
    if (files.length < 2) {
      message.warning('请至少上传两个PDF文件');
      return;
    }

    setError(null);
    try {
      setLoading(true);
      const response = await pdfApi.mergePDFs(files);
      downloadFile(response, 'merged.pdf');
      message.success('合并成功！');
      setFiles([]);
    } catch (err) {
      handleApiError(err);
      setError('合并失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    setFiles([]);
    setError(null);
  };

  return (
    <Card
      title="PDF合并"
      extra={
        <Button.Group>
          <Button
            type="primary"
            icon={<FileAddOutlined />}
            onClick={handleMerge}
            disabled={loading || files.length < 2}
          >
            合并文件
          </Button>
          <Button
            icon={<DeleteOutlined />}
            onClick={handleReset}
            disabled={loading || files.length === 0}
          >
            清空列表
          </Button>
        </Button.Group>
      }
    >
      {error ? (
        <Result
          status="error"
          title={error}
          extra={
            <Button type="primary" onClick={handleReset}>
              重试
            </Button>
          }
        />
      ) : (
        <>
          <FileUploader
            accept=".pdf"
            multiple
            onUpload={handleUpload}
            loading={loading}
            description="支持多个PDF文件，将按上传顺序合并"
          />

          {files.length > 0 && (
            <div style={{ marginTop: 16 }}>
              <h4>待合并文件列表：</h4>
              <ul style={{ 
                listStyle: 'none',
                padding: 0,
                maxHeight: '200px',
                overflow: 'auto'
              }}>
                {files.map((file, index) => (
                  <li
                    key={file.name + index}
                    style={{
                      padding: '8px',
                      background: '#f5f5f5',
                      marginBottom: '8px',
                      borderRadius: '4px',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignItems: 'center'
                    }}
                  >
                    <span>{`${index + 1}. ${file.name}`}</span>
                    <Button
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => {
                        setFiles(prev => prev.filter((_, i) => i !== index));
                      }}
                    />
                  </li>
                ))}
              </ul>
            </div>
          )}

          {loading && (
            <div style={{ textAlign: 'center', margin: '24px 0' }}>
              <Spin tip="正在合并中..." />
            </div>
          )}
        </>
      )}
    </Card>
  );
};

export default PDFMerger; 